package cn.ichiva.common.jwt.impl;

import cn.ichiva.common.jwt.JWTParser;
import io.jsonwebtoken.Jwts;

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.security.KeyFactory;
import java.security.NoSuchAlgorithmException;
import java.security.PublicKey;
import java.security.spec.InvalidKeySpecException;
import java.security.spec.X509EncodedKeySpec;

public class DefaultJWTParser implements JWTParser {
    public final PublicKey publicKey;

    public DefaultJWTParser(String path) throws IOException, NoSuchAlgorithmException, InvalidKeySpecException {
        this(Files.readAllBytes(Paths.get(path)));
    }

    public DefaultJWTParser(PublicKey publicKey) {
        this.publicKey = publicKey;
    }

    public DefaultJWTParser(byte[] publicKey) throws NoSuchAlgorithmException, InvalidKeySpecException {
        this.publicKey = KeyFactory.getInstance("RSA").generatePublic(new X509EncodedKeySpec(publicKey));
    }

    @Override
    public String parse(String jwt) {
        return Jwts.parser()
                .setSigningKey(publicKey)
                .parseClaimsJws(jwt)
                .getBody()
                .get("TEXT")
                .toString();
    }
}
